package com.xzp.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.deploy.net.URLEncoder;
import com.xzp.cmn.listener.DictListener;
import com.xzp.cmn.mapper.DictMapper;
import com.xzp.cmn.service.DictService;
import com.xzp.yygh.model.cmn.Dict;

import com.xzp.yygh.vo.cmn.DictEeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    //判断该id的子节点是否还有子节点
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    @Override
    public List<Dict> findChildData(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        // 根据父id来查询一类结果
        List<Dict> dictList = baseMapper.selectList(wrapper);
        //向list集合每个dict对象中设置hasChildren
        for (Dict dict: dictList) {
            Long dictId = dict.getId();
            boolean isChild = this.hasChildren(dictId);
            dict.setHasChildren(isChild);
        }
        return dictList;
    }


    // 将列表中的数据输出到excel文件中
    @Override
    public void exportDictData(HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("数据字典", "UTF-8");
            // 设置返回头为下载类型， 并规定下载文件的名称
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            List<Dict> dicts = this.baseMapper.selectList(null);
            ArrayList<DictEeVo> dictEeVoList = new ArrayList<>();
            for(Dict dict:dicts){
                DictEeVo dictEeVo = new DictEeVo();
                // 将dict属性注入dictEeVo中
                BeanUtils.copyProperties(dict, dictEeVo, DictEeVo.class);
                dictEeVoList.add(dictEeVo);
            }
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(dictEeVoList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 导入数据字典
    @CacheEvict(value = "dict", allEntries=true)
    @Override
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, new DictListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    //判断id下面是否有子节点
    private boolean hasChildren(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",id);
        Integer count = baseMapper.selectCount(wrapper);
        // 0>0    1>0
        return count>0;
    }


    /**
     * 根据dict_code与value一起查询获得对应值
     * @param parentDictCode
     * @param value
     * @return
     */
    @Cacheable(value = "dict",keyGenerator = "keyGenerator")
    @Override
    public String getNameByParentDictCodeAndValue(String parentDictCode, String value) {
    //如果value能唯一定位数据字典，parentDictCode可以传空，例如：省市区的value值能够唯一确定
        // 根据value唯一确定
        if(StringUtils.isEmpty(parentDictCode)) {
            Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("value", value));
            if(null != dict) {
                return dict.getName();
            }
        } else {
            // 根据parentDictcode和value唯一确定
            // 先获取父节点的信息
            Dict parentDict = this.getByDictsCode(parentDictCode);
            if(null == parentDict) return "";
            // 根据parent_id 和 value 查询
            Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("parent_id", parentDict.getId()).eq("value", value));
            if(null != dict) {
                return dict.getName();
            }
        }
        return "";
    }

    /**
     * 根据dictcode获取父节点
     * @param parentDictCode
     * @return
     */
    @Override
    public Dict getByDictsCode(String parentDictCode) {
        return baseMapper.selectOne(new QueryWrapper<Dict>().eq("dict_code", parentDictCode));
    }


    /**
     * 找到dict_code标签下所有的节点
     * @param dictCode
     * @return
     */
    @Override
    public List<Dict> findByDictCode(String dictCode) {
        // 先根据dictCode找到父节点
        Dict dict = baseMapper.selectOne(new QueryWrapper<Dict>().eq("dict_code", dictCode));
        // 保证父节点不为空
        if(Objects.isNull(dict)){
            return null;
        }
        // 再根据父节点id找到子节点
        List<Dict> child_dicts = this.findChildData(dict.getId());
        return child_dicts;
    }


}
